<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑发货订单' : '新增发货订单' }}</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-loading="loading">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入发货项目名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发货时间" prop="deliveryDate">
              <el-date-picker
                  v-model="form.deliveryDate"
                  type="date"
                  placeholder="选择发货日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%;"
              ></el-date-picker>

              <!--              <el-date-picker-->
              <!--                  type="date"-->
              <!--                  v-model="form.deliveryDate"-->
              <!--              placeholder="开始时间">-->
              <!--              </el-date-picker>-->

            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="中英文支持" prop="supportMultilang">
              <el-radio-group v-model="form.supportMultilang">
                <el-radio :label="true">支持</el-radio>
                <el-radio :label="false">不支持</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否正版软件" prop="isGenuine">
              <el-radio-group v-model="form.isGenuine">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="甲方地址" prop="clientAddress">
              <el-input v-model="form.clientAddress" placeholder="请输入甲方地址"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="甲方联系人" prop="clientContact">
              <el-input v-model="form.clientContact" placeholder="请输入甲方联系人"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方电话" prop="clientPhone">
              <el-input v-model="form.clientPhone" placeholder="请输入甲方电话"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发货公司名称">
              <el-input v-model="form.companyName" placeholder="请输入发货公司名称（选填）"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加密狗序列号">
              <el-input v-model="form.usbKeySerial" placeholder="请输入加密狗序列号（如适用）"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="form.isGenuine">
          <el-col :span="24">
            <el-form-item label="正版激活码">
              <el-input v-model="form.genuineActivationCode" placeholder="请输入正版系统激活码"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="!form.isGenuine">
          <el-col :span="24">
            <el-form-item label="软件名称备注">
              <el-input v-model="form.softwareNote" placeholder="请输入软件名称备注（非正版）"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目负责人" prop="leaderName">
              <el-input v-model="form.leaderName" placeholder="请输入项目负责人姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人部门" prop="leaderDepartment">
              <el-input v-model="form.leaderDepartment" placeholder="请输入负责人所在部门"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发货用途" prop="deliveryPurpose">
              <el-select v-model="form.deliveryPurpose" placeholder="请选择发货用途" style="width: 100%;">
                <el-option label="合同履行" value="合同履行"/>
                <el-option label="参展" value="参展"/>
                <el-option label="借用" value="借用"/>
                <el-option label="测试" value="测试"/>
                <el-option label="内部培训" value="内部培训"/>
                <el-option label="补充发货" value="补充发货"/>
                <el-option label="其他" value="其他"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否异常发货" prop="isAbnormalDelivery">
              <el-radio-group v-model="form.isAbnormalDelivery">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="form.isAbnormalDelivery">
          <el-col :span="24">
            <el-form-item label="异常原因说明" prop="abnormalReason">
              <el-input
                  type="textarea"
                  v-model="form.abnormalReason"
                  placeholder="请输入异常原因说明"
                  :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="form.deliveryPurpose === '补充发货'">
          <el-col :span="12">
            <el-form-item label="原始订单ID" prop="originalOrderId">
              <el-input v-model="form.originalOrderId" placeholder="请输入原始发货订单ID"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="上传附件">
              <el-upload
                  class="upload-demo"
                  action="/api/api/upload"
                  multiple
                  :limit="5"
                  :on-success="handleUploadSuccess"
                  :file-list="fileList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">支持JPG、PNG、PDF等文件，且不超过10MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {createDeliveryOrder, updateDeliveryOrder, getDeliveryOrderDetail} from '@/api/delivery';

export default {
  name: 'DeliveryOrderForm',
  data() {
    return {
      loading: false,
      isEdit: false,
      form: {
        id: undefined,
        projectName: '',
        deliveryDate: '',
        supportMultilang: false,
        clientAddress: '',
        clientContact: '',
        clientPhone: '',
        companyName: '',
        usbKeySerial: '',
        isGenuine: true,
        genuineActivationCode: '',
        softwareNote: '',
        leaderName: '',
        leaderDepartment: '',
        deliveryPurpose: '',
        isAbnormalDelivery: false,
        abnormalReason: '',
        attachmentPaths: '',
        originalOrderId: ''
      },
      fileList: [],
      rules: {
        projectName: [{required: true, message: '请输入发货项目名称', trigger: 'blur'}],
        deliveryDate: [{required: true, message: '请选择发货时间', trigger: 'change'}],
        supportMultilang: [{required: true, message: '请选择是否支持中英文', trigger: 'change'}],
        clientAddress: [{required: true, message: '请输入甲方地址', trigger: 'blur'}],
        clientContact: [{required: true, message: '请输入甲方联系人', trigger: 'blur'}],
        clientPhone: [{required: true, message: '请输入甲方电话', trigger: 'blur'}],
        isGenuine: [{required: true, message: '请选择是否为正版软件', trigger: 'change'}],
        leaderName: [{required: true, message: '请输入项目负责人姓名', trigger: 'blur'}],
        leaderDepartment: [{required: true, message: '请输入负责人所在部门', trigger: 'blur'}],
        deliveryPurpose: [{required: true, message: '请选择发货用途', trigger: 'change'}],
        isAbnormalDelivery: [{required: true, message: '请选择是否异常发货', trigger: 'change'}],
        abnormalReason: [
          {
            required: true, message: '请输入异常原因说明', trigger: 'blur',
            validator: (rule, value, callback) => {
              if (this.form.isAbnormalDelivery && !value) {
                callback(new Error('请输入异常原因说明'));
              } else {
                callback();
              }
            }
          }
        ],
        originalOrderId: [
          {
            required: true, message: '请输入原始发货订单ID', trigger: 'blur',
            validator: (rule, value, callback) => {
              if (this.form.deliveryPurpose === '补充发货' && !value) {
                callback(new Error('请输入原始发货订单ID'));
              } else {
                callback();
              }
            }
          }
        ]
      }
    };
  },
  created() {
    const id = this.$route.params.id;
    if (id) {
      this.isEdit = true;
      this.getDetail(id);
    }
  },
  methods: {
    getDetail(id) {
      this.loading = true;
      getDeliveryOrderDetail(id).then(response => {
        this.form = response.data;
        // 处理文件列表显示
        if (this.form.attachmentPaths) {
          const paths = this.form.attachmentPaths.split(',');
          this.fileList = paths.map(path => {
            const name = path.substring(path.lastIndexOf('/') + 1);
            return {name, url: path};
          });
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    handleUploadSuccess(response, file, fileList) {
      this.fileList = fileList;
      const path = response;
      this.form.attachmentPaths = path;
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true;
          const action = this.isEdit ? updateDeliveryOrder : createDeliveryOrder;
          action(this.form).then(response => {
            this.$message.success(response.msg || (this.isEdit ? '更新成功' : '创建成功'));
            this.goBack();
            this.loading = false;
          }).catch(() => {
            this.loading = false;
          });
        } else {
          this.$message.error('请填写必填项');
          return false;
        }
      });
    },
    goBack() {
      this.$router.push({path: '/delivery/list'});
    }
  }
};
</script>

<style scoped>
.el-select {
  width: 100%;
}
</style>
